package com.edgclub.edg.activity;


import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.edgclub.edg.Constant;
import com.edgclub.edg.R;
import com.edgclub.edg.api.UserApi;
import com.edgclub.edg.http.async.AsyncHttpResponseHandler;
import com.edgclub.edg.model.User;
import com.edgclub.edg.model.result.UserData;
import com.edgclub.edg.uc.CropImageView;
import com.edgclub.edg.utils.GlideUtil.GlideUtils;
import com.edgclub.edg.utils.util.BitmapUtility;
import com.edgclub.edg.utils.util.DateUtils;
import com.edgclub.edg.utils.util.DensityUtils;
import com.edgclub.edg.utils.util.JSONHelper;
import com.edgclub.edg.utils.util.JsonUtil;
import com.edgclub.edg.utils.util.UserPrefUtils;

import java.io.File;
import java.io.IOException;

import cz.msebera.android.httpclient.Header;
import me.nereo.multi_image_selector.bean.Image;

public class CutPhotoActivity extends GzBaseTooolBarActivity {


    // Views ///////////////////////////////////////////////////////////////////////////////////////
    private CropImageView mCropView;

    // Image file index(register_1 ~ 5)
    private int mImageIndex = 5;

    // Bundle key for Save/Restore state ///////////////////////////////////////////////////////////
    private static final String KEY_IMG_INDEX = "img_index";
    private Image selectImage;
    // Lifecycle Method ////////////////////////////////////////////////////////////////////////////
    private GlideUtils glideUtils;
    private String userPath = "";
    private boolean isload;
    private boolean isupdete;
    private UserPrefUtils userPrefUtils;
    private int selectType;
    @Override
    public int getContentView() {
        return R.layout.activity_cut_photo;
    }

    @Override
    public void setTitleBarView() {
        setCustomActionBar();
        title.setText("选择图片");
        right_layout.setVisibility(View.VISIBLE);
        right_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Bitmap bitmap=mCropView.getCroppedBitmap();
                if(null!=bitmap){
                    userPath = Constant.userIconDir+ DateUtils.getTimestampStr()+".jpg";
//                    userPath = Constant.userIconDir+ GuZhiApplication.getInstance().getUserId()+".jpg";
                    try {
                        BitmapUtility.saveFile(bitmap, userPath);
                        if(selectType==1)
                            checkNetworkState();
                        else{
                            Intent intent=new Intent(CutPhotoActivity.this,MultiImageSelectorActivity.class);
                            if(!"".equals(userPath)) {
                                intent.putExtra("userPath", userPath);
                            }
                            setResult(RESULT_OK, intent);
                            finish();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        right_text.setText("完成");
    }

    @Override
    public void initView() {
        userPrefUtils=  new UserPrefUtils(CutPhotoActivity.this);
        // bind Views
        mCropView = (CropImageView) findViewById(R.id.cropImageView);
        mCropView.setCropMode(CropImageView.CropMode.RATIO_1_1);
        mCropView.setScaleType(ImageView.ScaleType.FIT_CENTER);

    }

    @Override
    public void initData() {
        // set bitmap to CropImageView
        selectType=getIntent().getIntExtra("selectType",1);
        selectImage= (Image) getIntent().getSerializableExtra(MultiImageSelectorActivity.EXTRA_RESULT);
        isupdete=getIntent().getBooleanExtra("isupdete",false);
        glideUtils=new GlideUtils();
        if(null==selectImage){
            Toast.makeText(CutPhotoActivity.this,"图片加载失败，请重新选择",Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        new LoadImageAsyncTask().execute(selectImage.path);

    }

    private boolean checkNetworkState() {
        boolean flag = false;
        //得到网络连接信息
        ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        //去进行判断网络是否连接
        if (manager.getActiveNetworkInfo() != null) {
            flag = manager.getActiveNetworkInfo().isAvailable();
        }
        if (!flag) {
            Toast.makeText(CutPhotoActivity.this,"网络异常，请稍后再试",Toast.LENGTH_SHORT).show();
        } else {
            uploadImage();
        }

        return flag;
    }


    private void uploadImage(){
        if(isload)return;

        if(!"".equals(userPath)) {
             File file = new File(userPath);
            if(!file.exists()){
                Toast.makeText(CutPhotoActivity.this,"图片加载失败，请重新选择",Toast.LENGTH_SHORT).show();
                return;
            }



            showDialog("保存中，请稍后...",false);
//            dialog.setCanceledOnTouchOutside(false);
            new UserApi(this).userUpload(file, new AsyncHttpResponseHandler() {

                @Override
                public void onStart() {
                    isload=true;
                }

                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    isload=false;
                    dismissDialog();
                    try {
                        String recString= null;
                        recString = new String(responseBody ,"UTF-8");

                        Log.d("recString",recString);
                        if (JSONHelper.isSuccess(recString)) {
                            UserData userData= JsonUtil.getMode(recString,UserData.class);
                            if(null!=userData&&null!=userData.getData()){
                                Toast.makeText(CutPhotoActivity.this,"头像上传成功",Toast.LENGTH_SHORT).show();
                                Intent intent=new Intent(CutPhotoActivity.this,MultiImageSelectorActivity.class);
                                userPath=userData.getData().getLogo();
                                if(!"".equals(userPath)) {
                                    User u = userPrefUtils.getUser();
                                    u.setLogo(userPath);
                                    u.setHdLogo(userData.getData().getHdLogo());
                                    userPrefUtils.saveUser(u);
                                    intent.putExtra("userPath", userPath);
                                }
                                setResult(RESULT_OK, intent);
                                finish();
                            }
                        }
                    } catch (Exception e) {
                        Toast.makeText(CutPhotoActivity.this,"网络异常，请稍后再试",Toast.LENGTH_SHORT).show();
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                    dismissDialog();
                    isload=false;
                    Toast.makeText(CutPhotoActivity.this,"网络异常，请稍后再试",Toast.LENGTH_SHORT).show();
                }
            });

        }


    }
    /**
     * load图片
     *
     *
     */
    class LoadImageAsyncTask extends AsyncTask<String, Void, Bitmap> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showDialog("正在加载", true);

        }

        @Override
        protected Bitmap doInBackground(String... uris) {
            int w=DensityUtils.getScreenW(CutPhotoActivity.this);
            int h=DensityUtils.getScreenH(CutPhotoActivity.this);
            return glideUtils.Glide_getBitmap(CutPhotoActivity.this,selectImage.path,w ,h);
        }
        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            if(null!=bitmap)
                mCropView.setImageBitmap(bitmap);
            else {
                Toast.makeText(CutPhotoActivity.this,"图片加载失败，请重新选择",Toast.LENGTH_SHORT).show();
                finish();
            }
            dismissDialog();
        }

    }

    // Switch image files //////////////////////////////////////////////////////////////////////////

    private void incrementImageIndex() {
        mImageIndex++;
        if (mImageIndex > 5) mImageIndex -= 5;
    }

    public Bitmap getImageForIndex(int index) {
        String fileName = "sample" + index;
        int resId = getResources().getIdentifier(fileName, "mipmap", getPackageName());
        return BitmapFactory.decodeResource(getResources(), resId);
    }

    /*private final View.OnClickListener btnListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            switch (v.getId()) {
                case R.id.buttonDone:

                    // Start ResultActivity
                    Intent intent = new Intent(CutPhotoActivity.this, CutPhotoResultActivity.class);
                    startActivity(intent);
                    break;
                case R.id.buttonFitImage:
                    mCropView.setCropMode(CropImageView.CropMode.RATIO_FIT_IMAGE);
                    break;
                case R.id.button1_1:
                    mCropView.setCropMode(CropImageView.CropMode.RATIO_1_1);
                    break;
                case R.id.button3_4:
                    mCropView.setCropMode(CropImageView.CropMode.RATIO_3_4);
                    break;
                case R.id.button4_3:
                    mCropView.setCropMode(CropImageView.CropMode.RATIO_4_3);
                    break;
                case R.id.button9_16:
                    mCropView.setCropMode(CropImageView.CropMode.RATIO_9_16);
                    break;
                case R.id.button16_9:
                    mCropView.setCropMode(CropImageView.CropMode.RATIO_16_9);
                    break;
                case R.id.buttonCustom:
                    mCropView.setCustomRatio(7, 5);
                    break;
                case R.id.buttonFree:
                    mCropView.setCropMode(CropImageView.CropMode.RATIO_FREE);
                    break;
                case R.id.buttonCircle:
                    mCropView.setCropMode(CropImageView.CropMode.CIRCLE);
                    break;
                case R.id.buttonChangeImage:
                    incrementImageIndex();
                    mCropView.setImageBitmap(getImageForIndex(mImageIndex));
                    break;
                case R.id.buttonRotateImage:
                    mCropView.rotateImage(CropImageView.RotateDegrees.ROTATE_90D);
                    break;
            }
        }
    };*/
}
